const express = require('express')
const mysql = require('mysql')
const router = express.Router()
const address = require('../MySql/index')
const sql = mysql.createConnection(address.mysql);
sql.connect(function (err) {
    if(err){
        console.log(err)
    }else {
        console.log('链接成功')
    }
});
// 获取用户信息
// 获取用户信息
router.get('/getUser', (req, res, next) => {
    const id = req.query.sonId
    if (id == undefined) {
        res.status(400).send('无权限')
    }
    // ID 为0时，获取所有用户信息, 角色：管理员
    if (id == 0) {
        sql.query('SELECT * FROM user_info', (err, results) => {
            if (err) {
                console.error('Error executing query:', err)
                res.status(500).json({ error: 'Internal Server Error' })
            } else {
                let data = {
                    code: 200,
                    data: results,
                    message: '查询成功'
                }
                res.status(200)
                res.json(data)
            }
        })
    } else {
        // 查询对应账户的子数据
        sql.query('SELECT * FROM user_info WHERE roleId = ?', [id], (err, results) => {
            if (err) {
                console.error('Error executing query:', err)
                res.status(500).json({ error: 'Internal Server Error' })
            } else {
                let data = {
                    code: 200,
                    data: results,
                    message: '查询成功'
                }
                res.status(200)
                res.json(data)
            }
        })
    }
})

// 登陆
router.post('/login', async (req, res, next) => {
    console.log(req.body)
    // 登录查询手机号和密码是否正确
    const phone = req.body.phone
    const password = req.body.password
    if (!phone || !password) {
        return res.status(400).json({ message: '手机号或密码不能为空' })
    }
    // 查询用户名和密码是否正确
    const [results] = await new Promise((resolve, reject) => {
        sql.query('SELECT * FROM user_account WHERE phone = ?', [phone], (err, results) => {
            if (err) {
                reject(err)
            } else {
                resolve(results)
            }
        })
    })
    if (results && results.length === 0) {
        return res.status(400).json({ message: '手机号或密码错误' })
    } else {
        // 查询用户信息
        await new Promise((resolve, reject) => {
            sql.query('SELECT * FROM user_info WHERE phone = ?', phone, (err, results) => {
                if (err) {
                    reject(err)
                    res.status(400).json({ message: '未查询到用户信息' })
                } else {
                    resolve(results)
                    res.status(200).json({
                        code: 200,
                        data: results[0],
                        success: true,
                        message: '登陆成功'
                    })
                }
            })
        })
    }
})

module.exports = router